package com.xc.otc

import android.content.Context
import android.content.DialogInterface
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.RelativeLayout
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.DialogFragment

/**
 * @author by mk
 * Date on 2020/11/20
 * Description:
 */
open abstract class AbstractFragmentDialog<T : ViewDataBinding?> : DialogFragment {

    private var mContext: Context? = null

    protected var mDataBinding: T? = null

    //返回键是否关闭弹窗
    protected var dismissOnBackPressed = true

    // 弹窗外部是否关闭弹窗
    protected var dismissOnTouchOutside = true


    protected var rootView: View? = null

    protected var sureListener: SureListener? = null


    constructor() {}
    constructor(dismissOnBackPressed: Boolean, dismissOnTouchOutside: Boolean) {
        this.dismissOnBackPressed = dismissOnBackPressed
        this.dismissOnTouchOutside = dismissOnTouchOutside
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, themeStyle)

    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
//        hideNativeBar()
        // 弹出框外面是否可取消
        dialog?.setCanceledOnTouchOutside(dismissOnTouchOutside)

        // 返回true表示消费事件，拦截
        dialog!!.setOnKeyListener { _: DialogInterface?, keyCode: Int, _: KeyEvent? ->
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                //不往上传递则关闭不了，默认是可以取消，即return false，
                if (dismissOnBackPressed) {
                    onBackPressDismissBefore()
                }
                return@setOnKeyListener !dismissOnBackPressed
            } else {
                return@setOnKeyListener false
            }
        }
        if (isUseDataBinding) {
            mDataBinding = DataBindingUtil.inflate<T>(inflater, layoutId, container, false)
            if (mDataBinding != null) {
                rootView = mDataBinding!!.root
            }
        } else {
            rootView = inflater.inflate(layoutId, container)
        }
        val rl = RelativeLayout(context)
        val pm = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        rl.layoutParams = pm
        //        rl.setGravity(Gravity.CENTER);
        rl.addView(rootView, pm)
        if (dismissOnTouchOutside) {
            rl.setOnClickListener { disMissDialog() }
        }
        initView()
        return rl
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //解决底部导航栏问题：在弹出dialog得时候出现导航栏
        dialog?.let {
            it.window?.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);

            /**
             * 在DialogFragment显示后,去掉这个FLAG_NOT_FOCUSABLE.去掉这个标志后,
             * DialogFragment重新获取到焦点,所以点击周围可以关闭掉他.
             * 同时,底部导航栏这个时候又会显示出来, 所以要在DialogFragment显示的onShow()的时候,再次调用设置全屏的方法,设置为全屏.
             */
            it.setOnShowListener { dg ->
                it.window?.setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN
                );
                val uiOptions =
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                            View.SYSTEM_UI_FLAG_IMMERSIVE or
                            View.SYSTEM_UI_FLAG_FULLSCREEN;
                it.window?.decorView?.systemUiVisibility = uiOptions;
            }
        }


    }


    override fun onStart() {
        super.onStart()
        //获取手机屏幕的长和宽
        mContext = context
        if (mContext != null) {
            val displayMetrics = mContext!!.resources.displayMetrics
            val width = displayMetrics.widthPixels

            //这个设置宽高的必须放在onstart方法里，不能放oncreateview里面
            val dialogWindow = dialog!!.window
            val lp = dialogWindow!!.attributes

            // 布局文件居中
            dialogWindow.setGravity(Gravity.CENTER)
//            lp.windowAnimations = animId
            // dialogWindow.setLayout(lp.MATCH_PARENT, lp.WRAP_CONTENT);// 为了让对话框宽度铺满
            //设置弹窗的宽度，
            lp.width = width
            lp.height = WindowManager.LayoutParams.MATCH_PARENT
            //lp.alpha = 0.1f;
            dialogWindow.attributes = lp

        }


    }


    private fun hideNativeBar() {
        try {
            dialog?.window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            dialog?.window?.decorView?.setOnSystemUiVisibilityChangeListener {
                var uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or  //布局位于状态栏下方
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or  //全屏
                        View.SYSTEM_UI_FLAG_FULLSCREEN or  //隐藏导航栏
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

                uiOptions = if (Build.VERSION.SDK_INT >= 19) {
                    uiOptions or 0x00001000
                } else {
                    uiOptions or View.SYSTEM_UI_FLAG_LOW_PROFILE
                }
                dialog!!.window!!.decorView.systemUiVisibility = uiOptions
            }
        } catch (e: Exception) {

        }
    }


    private val themeStyle: Int
        private get() =
            if (isBackgroundDim) R.style.BaseFkDialogStyle else R.style.BaseFkDialogNoBackground


    /**
     * 背景色是否变暗
     *
     */
    open var isBackgroundDim: Boolean = true;


    /**
     * 布局文件id
     *
     * @return 返回布局文件Layout 的id
     */
    protected abstract val layoutId: Int

    /**
     * 初始化布局
     */
    protected abstract fun initView()

    /**
     * 使用dataBinding 需要泛型传入，不使用dataBing，返回false
     *
     * @return true:使用dataBinding
     */
    protected abstract val isUseDataBinding: Boolean

    fun disMissDialog() {
        dismissAllowingStateLoss()
    }

    /**
     * 调用返回键，弹窗消失前调用
     */
    fun onBackPressDismissBefore() {}
    override fun onDestroy() {
        super.onDestroy()
    }


    interface SureListener {
        fun onSure()
    }

    interface CancelListener {
        fun onCancel()
    }

    interface CloseListener {
        fun onClose()
    }

}